package com.hdrx.fundhelper.config;

import com.hdrx.fundhelper.common.R;
import com.hdrx.fundhelper.dao.pojo.Userinfo;
import com.hdrx.fundhelper.inter.RedisCache;
import com.hdrx.fundhelper.service.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;


/**
 * @author: houdx
 * @description:
 * @date: 2023/7/28 14:19
 */
@Aspect
@Component
@Slf4j
public class RedisCacheAspect {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserService userService;

    @Before(value = "@annotation(redisCache)")
    public R cache(JoinPoint jp, RedisCache redisCache) {
        log.info(".......先执行了次方法去查缓存......");

        //获取拦截方法的入参
        Object[] args = jp.getArgs();
        Integer id = (Integer) args[0];
        log.info("获取拦截方法的入参:{}", id);

        //先从缓存中查询数据
        ValueOperations value = redisTemplate.opsForValue();
        Object o = value.get(String.valueOf(id));
        R r = new R();
        if (null != o) {
            log.info("从缓存中查询的数据{}", o);
            //直接返回
             r.setBody(o);
             return r;
        }
        Userinfo userinfo = userService.queryUserById(id);
        value.set(id,userinfo);
        r.setBody(userinfo);
        return r;
    }


}
